<template>
	<view class="bigBox">
		<u-navbar :fixed="false" :placeholder="true" title="审核通过" @leftClick="leftClick" bgColor="#0F53AC"
			leftIconColor="#fff">
		</u-navbar>
		<view class="kiss-list">
			<view class="kiss-list-title2">
				<view class="left">
					<view style="color: red;" v-if="isInspec == 0">*</view>
					隐患位置
				</view>
				<view class="right1" v-if="isInspec == 0" @click="handleUnit()">
					<view class="iconfont icon-app-add sm-sd">请选择</view>
				</view>
			</view>
			<view class="kiss-list-input" v-if="isInspec == 0">
				<u--textarea :autoHeight="true" inputAlign="left" maxlength="32" v-model="dataForm.dangerSite" placeholder="请输入隐患位置">
				</u--textarea>
			</view>
			<view class="textInput" style="padding:0 32rpx;color: #8c8c8c;" v-else>{{dataForm.dangerSite || '无'}}
			</view>
		</view>
		<view class="kiss-title">
			<view class="left">
				隐患照片
			</view>
		</view>
		<view class="kiss-upload">
			<view class="imgBox" v-if="fileList1.length">
				<view class="img" v-for="v in imgList">
					<image @tap="previewImage(v,imgList)" :src="v"></image>
				</view>
				<video class="video" v-for="v in videoList" :src="v"></video>
			</view>
			<view v-else class="text">无</view>
		</view>
		<view class="kiss-upDown-list">
			<view class="bx-list-title">
				<view class="left">
					<view class="yz" v-if="isInspec == 0">*</view>
					隐患描述
				</view>
			</view>
			<view class="input-textrea" v-if="isInspec == 0">
				<u--textarea class="textrea" v-model="dataForm.dangerDesc" placeholder="请输入隐患描述" maxlength="1000">
				</u--textarea>
			</view>
			<view class="textInput" v-else>{{dataForm.dangerDesc || '无'}}</view>
		</view>
		<view class="kiss-list">
			<view class="kiss-list-title" @click="showReason = true">
				<view class="left">
					隐患形成原因
				</view>
				<view class="right1" v-if="isInspec == 0">
					<view :class="[dataForm.dangerReason != '' ? 'select-bg' : 'sel']">
						{{ dataForm.dangerReason != '' ? dangerReasonData[dataForm.dangerReason - 1] : '请选择' }}
					</view>
					<u-icon name="arrow-right"></u-icon>
				</view>
				<view class="right1" v-else>
					<view :class="[dataForm.dangerReason != '' ? 'select-bg' : '']">
						{{ dataForm.dangerReason != '' ? dangerReasonData[dataForm.dangerReason - 1] : '无' }}
					</view>
				</view>
			</view>
		</view>

		<view class="kiss-upDown-list">
			<view class="bx-list-title">
				<view class="left">
					<view class="yz" v-if="isInspec == 0">*</view>
					隐患等级
				</view>
			</view>
			<view class="bx-list-title"  style="margin-top: 24rpx;">
				<u-radio-group v-model="dataForm.dangerLevel" placement="row">
					<u-radio :label="'一般隐患'" :name="1" activeColor="#0F53AC" :labelColor="dataForm.dangerLevel==1 ? '#0F53AC':''">
					</u-radio>
					<u-radio :customStyle="{marginLeft: '100rpx'}" :label="'重大隐患'" :name="2" activeColor="#0F53AC" :labelColor="dataForm.dangerLevel==2 ? '#0F53AC':''">
					</u-radio>
				</u-radio-group>
			</view>
		</view>
		<u-gap height="6" bgColor="#f2f2f2"></u-gap>
		<view class="kiss-upDown-list">
			<view class="bx-list-title">
				<view class="left">
					整改意见
				</view>
			</view>
			<view class="input-textrea" v-if="isInspec == 0">
				<u--textarea class="textrea" v-model="dataForm.suggestion" placeholder="请输入整改意见" maxlength="1000">
				</u--textarea>
			</view>
			<view class="textInput" v-else>{{dataForm.suggestion || '无'}}</view>
		</view>
		<u-gap height="6" bgColor="#f2f2f2"></u-gap>
		<view class="kiss-list">

			<view class="kiss-list-title" @click="handleUser">
				<view class="left">
					<view class="yz" v-if="isInspec == 0">*</view>
					整改人
				</view>
				<view class="right1" v-if="isInspec == 0">
					<view :class="[dataForm.realRectify != '' ? 'select-bg' : 'sel']">
						{{ dataForm.realRectify != '' ? dataForm.realRectify : '请选择' }}
					</view>
					<u-icon name="arrow-right" class="sel"></u-icon>
				</view>
				<view class="right1" v-else>
					<view :class="[dataForm.realRectify != '' ? 'select-bg' : '']">
						{{ dataForm.realRectify != '' ? dataForm.realRectify : '无' }}
					</view>
				</view>
			</view>
			<view class="kiss-list-title" @click="showTime = true">
				<view class="left">
					<view class="yz" v-if="isInspec == 0">*</view>
					整改时限
				</view>
				<view class="right1" v-if="isInspec == 0">
					<view :class="[dataForm.limitDate ? 'select-bg' : 'sel']">
						{{ dataForm.limitDate ? dataForm.limitDate : '请选择' }}
					</view>
					<view class="iconfont icon-app-xiangyou sel"></view>
				</view>
				<view class="right1" v-else>
					<view :class="[dataForm.limitDate ? 'select-bg' : '']">
						{{ dataForm.limitDate ? dataForm.limitDate : '无' }}
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-subside"></view>
		<view class="kiss-bottom-once">
			<view class="btn-right" @click="$dianji(sumbit,'onoff')">确定</view>
		</view>

		<!-- 整改部门 -->
		<u-popup :show="showBumen" mode="bottom" :round="10">
			<view class="kiss-popup">
				<view class="picker-btn">
					<view class="left" @click="cancelBumen">取消</view>
					<view class="right" @click="confirmBumen">确定</view>
				</view>
				<picker-view :indicator-style="indicatorStyle" :value="valueArr" @change="bindChange">
					<picker-view-column>
						<view class="item" v-for="(item,index) in province" :key="item.id">{
							<!-- -->{item.deptName}}
						</view>
					</picker-view-column>
					<picker-view-column v-if="province[valueArr[0]]">
						<view class="item" v-for="(item,index) in province[valueArr[0]].children" :key="item.id">
							{
							<!-- -->{item.deptName}}
						</view>
					</picker-view-column>
				</picker-view>
			</view>
		</u-popup>
		<u-picker :show="showUser" :columns="userColumns" keyName="name" @confirm="onChangeUser" @cancel="cancelUser">
		</u-picker>
		<u-datetime-picker :disabled="isInspec != 0" :minDate="value4" :show="showTime" :value="value4" mode="date" @cancel="cancelTime"
			@confirm="confirmTime">
		</u-datetime-picker>

		<!-- 隐患形成原因 -->
		<u-picker :show="showReason" :columns="reasonColumns" keyName="name" @confirm="onChangeReason"
			@cancel="cancelReason">
		</u-picker>
		<!-- 隐患位置 -->
		
		<tki-tree ref="tkitree" :range="treeList" rangeKey="configValue" idKey="id" :selectParent="true"
			confirmColor="#0F53AC" @confirm="confirmTree" />
	</view>
</template>

<script>
	import tkiTree from "../components/tki-tree/tki-tree.vue"
	export default {
		components: {
			tkiTree
		},
		data() {
			return {
				isInspec: 0, // 0 编辑 1 查看详情
				showBumen: false,
				dataForm: {},
				oldDataForm: {},
				onoff: true,
				fileList1: [],
				imgList: [],
				videoList: [],
				sourceType: ['album', 'camera'],
				showTime: false,
				value4: Number(new Date()),
				// 部门数据
				showBumen: false,
				indicatorStyle: `height: ${Math.round(uni.getSystemInfoSync().screenWidth/(750/100))}px;`,
				valueArr: [0, 0], // 用于判断当前滑动的是哪一列
				province: [], // 数据列表
				// 负责人数据
				showUser: false,
				userColumns: [],
				treeList: [],
				// 时间数据
				showTime: false,
				value4: Number(new Date()),
				showReason: false,
				dangerReasonData: ['人的不安全行为', '物的不安全状态', '管理缺陷', '环境与场所', '其他'],
				reasonColumns: [
					[{
							id: 1,
							name: '人的不安全行为'
						},
						{
							id: 2,
							name: '物的不安全状态'
						},
						{
							id: 3,
							name: '管理缺陷'
						},
						{
							id: 4,
							name: '环境与场所'
						},
						{
							id: 5,
							name: '其他'
						},
					]
				],
			};
		},
		onLoad(options) {
			this.randomId = options.randomId
			// 部门树数据
			this.getBumenData()
			this.initData()

			// 整改人员选择回调
			uni.$on('setUser', (data) => {
				this.dataForm.rectifyDeptId = data.parentId
				this.dataForm.rectifyDeptName = data.deptName
				this.dataForm.rectifyUid = data.id
				this.dataForm.rectifyName = data.name
				this.dataForm.realRectify = data.deptName + '-' + data.name
			})
			
			// 单元选择回调
			uni.$on('setUnit', (data) => {
				this.dataForm.dangerSite = data.configValue
			})
		},
		onShow() {
			this.getRegionData('')
		},
		methods: {
			leftClick() {
				let flag = this.deepCompare(this.dataForm, this.oldDataForm)
				if (flag) {
					uni.navigateBack({
						delta: 1
					})
					return
				}
				uni.showModal({
					title: '提示',
					content: '随手拍审核内容尚未提交保存,您确定要退出？',
					confirmText: '确定',
					cancelText: '取消',
					success: function(res) {
						if (res.confirm) {
							uni.navigateBack({
								delta: 1
							})
						}
					}
				});
			},
			getRegionData(k) {
				let params = {
					configType: 'risk_unit',
					keyword: k
				}
				uni.$u.http.post(`/check/pc/riskPoint/getRiskUnit`, params).then(res => {
					if (res.code == 0) {
						this.treeList = res.data
					}
				})
			},
			deepCompare(x, y) {
				var i, l, leftChain, rightChain;

				function compare2Objects(x, y) {
					var p;

					// remember that NaN === NaN returns false
					// and isNaN(undefined) returns true
					if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
						return true;
					}

					// Compare primitives and functions.     
					// Check if both arguments link to the same object.
					// Especially useful on the step where we compare prototypes
					if (x === y) {
						return true;
					}

					// Works in case when functions are created in constructor.
					// Comparing dates is a common scenario. Another built-ins?
					// We can even handle functions passed across iframes
					if ((typeof x === 'function' && typeof y === 'function') ||
						(x instanceof Date && y instanceof Date) ||
						(x instanceof RegExp && y instanceof RegExp) ||
						(x instanceof String && y instanceof String) ||
						(x instanceof Number && y instanceof Number)) {
						return x.toString() === y.toString();
					}

					// At last checking prototypes as good as we can
					if (!(x instanceof Object && y instanceof Object)) {
						return false;
					}

					if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
						return false;
					}

					if (x.constructor !== y.constructor) {
						return false;
					}

					if (x.prototype !== y.prototype) {
						return false;
					}

					// Check for infinitive linking loops
					if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
						return false;
					}

					// Quick checking of one object being a subset of another.
					// todo: cache the structure of arguments[0] for performance
					for (p in y) {
						if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
							return false;
						} else if (typeof y[p] !== typeof x[p]) {
							return false;
						}
					}

					for (p in x) {
						if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
							return false;
						} else if (typeof y[p] !== typeof x[p]) {
							return false;
						}

						switch (typeof(x[p])) {
							case 'object':
							case 'function':

								leftChain.push(x);
								rightChain.push(y);

								if (!compare2Objects(x[p], y[p])) {
									return false;
								}

								leftChain.pop();
								rightChain.pop();
								break;

							default:
								if (x[p] !== y[p]) {
									return false;
								}
								break;
						}
					}

					return true;
				}

				if (arguments.length < 1) {
					return true; //Die silently? Don't know how to handle such case, please help...
					// throw "Need two or more arguments to compare";
				}
				for (i = 1, l = arguments.length; i < l; i++) {
					leftChain = []; //Todo: this can be cached
					rightChain = [];
					if (!compare2Objects(arguments[0], arguments[i])) {
						return false;
					}
				}
				return true;
			},
			getBumenData() {

				uni.$u.http.get(`/base/mobile/sysDeptInfo/deptTreeList`).then(res => {
					if (res.code == 0) {
						this.province = res.data
					}
				}).catch(err => {})
			},
			initData() {
				uni.$u.http.get(`/check/mobile/appSmallTake/smallTakeDetail/${this.randomId}`).then(res => {
					if (res.code == 0) {
						this.dataForm = res.data
						this.dataForm.realRectify = res.data.rectifyName ? (res.data.rectifyDeptName + '-' + res
							.data.rectifyName) : ''
						this.oldDataForm = JSON.parse(JSON.stringify(res.data))
						if (res.data.dangerPhoto != '') {
							// 图片回显
							let arr = []
							res.data.dangerPhoto.split(',').map(item => {
								let dd = {
									url: item
								}
								arr.push(dd);
							})
							this.fileList1 = arr
							this.fileList1.forEach(item => {
								let str = item.url.split('?')[0]
								if (str.substring(str.length - 3, str.length) == 'mp4') {
									this.videoList.push(item.url)
								} else {
									this.imgList.push(item.url)
								}
							})
						} else {
							this.fileList1 = []
						}
					}
				}).catch(err => {})
			},
			sumbit() {
				const {
					dangerLevel,
					dangerSite,
					dangerDesc,
					suggestion,
					rectifyDeptId,
					rectifyDeptName,
					rectifyUid,
					rectifyName,
					limitDate,
					dangerReason, //隐患形成原因
				} = this.dataForm

				const params = {
					auditStatus: 1,
					id: this.randomId,
					dangerLevel,
					dangerSite,
					dangerDesc,
					suggestion,
					rectifyDeptId, // 整改部门id
					rectifyDeptName, // 整改部门名称
					rectifyUid,
					rectifyName, //整改人姓名
					limitDate,
					dangerReason
				}

				if (params.dangerSite == '') {
					uni.$u.toast("请填写隐患位置")
					return
				} else if (params.dangerDesc == '') {
					uni.$u.toast("请填写隐患描述")
					return
				} else if (params.dangerLevel == '') {
					uni.$u.toast("请选择隐患等级")
					return
				} else if (params.rectifyUid == '') {
					uni.$u.toast("请选择整改人")
					return
				} else if (params.limitDate == '') {
					uni.$u.toast("请选择整改时限")
					return
				}
				uni.$u.http.post(`/check/mobile/appSmallTake/approveSmallTake`, params).then(res => {
					if (res.code == 0) {
						uni.$u.toast('提交成功')
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							})
						}, 1000)
					}
				}).catch(err => {})
			},

			//确定选择部门
			confirmBumen() {
				let province = this.province[this.valueArr[0]]
				let rectifyDept = province.children[this.valueArr[1]]
				this.dataForm.rectifyDeptId = rectifyDept.id
				this.dataForm.rectifyDeptName = rectifyDept.deptName
				this.showBumen = false

				uni.$u.http.get(`/base/mobile/userInfo/getUserListByDeptId/${rectifyDept.id}`).then(res => {
					if (res.code == 0) {
						this.userColumns = [res.data]
					}
				}).catch(err => {})
			},
			cancelBumen() {
				this.showBumen = false
			},
			//选择部门联机
			bindChange(e) {
				const val = e.detail.value
				this.valueArr = val
			},
			// 选择负责人
			handleUser() {
				uni.navigateTo({
					url: `/pages/subPackagesA/riskIdtion/userTree`
				})
			},
			onChangeUser(e) {
				if (e.value[0]) {
					this.dataForm.rectifyName = e.value[0].name
					this.dataForm.rectifyUid = e.value[0].id
				}

				this.showUser = false
			},
			cancelUser() {
				this.showUser = false
			},
			// 选择时间
			cancelTime(e) {
				this.showTime = false;
			},
			confirmTime(e) {
				this.showTime = false;
				const timeFormat = uni.$u.timeFormat;
				let timeValue = timeFormat(e.value, 'yyyy-mm-dd');
				this.dataForm.limitDate = timeValue;
			},
			onChangeReason(e) {
				this.dataForm.dangerReason = e.value[0].id
				this.showReason = false
			},
			cancelReason() {
				this.showReason = false
			},
			//预览图片
			previewImage: function(e, s) {
				let imgList = []
				if (s.pictures) {
					imgList = this.getpictureList(s.pictures)
				} else {
					imgList = s
				}
				uni.previewImage({
					current: e,
					urls: imgList,
				});
			},
			//处理图片
			getpictureList(pictureinfo) {
				if (pictureinfo) {
					var splitAdd = pictureinfo.split(",");
					var imgList = []
					for (let i = 0; i < splitAdd.length; i++) {
						let iOrV = splitAdd[i].split("?")[0].split(".")
						let iOrVL = splitAdd[i].split("?")[0].split(".").length - 1
						if (iOrV[iOrVL] != 'mp4') {
							imgList.push(splitAdd[i])
						}
					}
					return imgList
				} else {
					return []
				}
			},
			//选择隐患位置
			handleUnit() {
				if (this.treeList.length != 0) {
					uni.navigateTo({
						url: `/pages/subPackagesA/riskIdtion/unitTree`
					})
				} else {
					this.tipShow = true
				}
				
			},
			confirmTree(e) {
				if (e[0]) {
					this.dataForm.dangerSite = e[0].configValue
				}
			},
		},
	}
</script>

<style scoped lang="scss">
	.bigBox {

		.title {
			padding: 32rpx;
			margin-right: 16rpx;
			word-break: break-all;
			word-wrap: break-word;
		}

		.box {
			padding: 0 20rpx;
		}

		.bx-upload {
			padding: 20rpx 30rpx;
			background: #fff;
			border-bottom: 1px solid #d6d7d9;
		}

	}
	
	.imgBox {
		display: flex;
	
		.img {
			width: 27vw;
			height: 27vw;
			margin-bottom: 4vw;
			margin-right: 4vw;
	
			image {
				width: 100%;
				height: 100%;
			}
		}
	
		.video {
			width: 27vw;
			height: 27vw;
			margin-bottom: 4vw;
			margin-right: 4vw;
		}
	}
	
	.yz{
		color: red;
	}
	
	.sel{
		color: #8C8C8C;
	}
</style>
